package com.bw.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.bw.entity.Enterprise;
import com.bw.mapper.EnterpriseMapper;
import com.bw.service.EnterpriseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EnterpriseServiceImpl implements EnterpriseService {

    @Autowired
    EnterpriseMapper enterpriseMapper;

    //接口保存方法添加事务处理
    @Transactional
    @Override
    public Enterprise add(Enterprise enterprise) {


        //所有输入项非空字段  9个字段
        Assert.notBlank(enterprise.getNum(),"纳税人识别号不为空");
        Assert.notBlank(enterprise.getName(),"公司名不为空");
        Assert.notBlank(enterprise.getPhone(),"手机号不为空");
        Assert.notBlank(enterprise.getEmail(),"邮箱不为空");
        Assert.notBlank(enterprise.getAddress(),"地址不为空");

        Assert.notNull(enterprise.getFlag(),"合同公司必填");

        //纳税人识别号查询数据库，完成唯一性校验
        Enterprise  enterpriseFromDB = enterpriseMapper.getByNum(enterprise.getNum());

        if (enterpriseFromDB != null){
            throw new RuntimeException("纳税人识别号重复！");
        }
        //“设为合同公司”，输入值为0或1
        if (enterprise.getFlag() != 0 && enterprise.getFlag() != 1){
            throw new RuntimeException("“设为合同公司”，输入值为0或1");
        }
        //打印方法参数到控制台
        System.out.println("方法的参数是 " + JSON.toJSONString(enterprise));

        System.out.println("添加之前打印主键id" + enterprise.getId());
        enterpriseMapper.add(enterprise);
        System.out.println("添加之后打印主键id" +  enterprise.getId());

        return enterprise;

    }

    @Override
    public Enterprise selectByNum(String num) {
        return enterpriseMapper.getByNum(num);
    }
}
